package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public String login(User user) {
        // 因为数据库中的密码是经过md5加密的  所以要将接受到的密码转换为 md5 加密的格式
        String password = user.getPassword();
        byte[] bytes = password.getBytes();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5DigestAsHex);
        // 将转换后的密码与数据库中的进行比较
        User user1 = userMapper.findByUP(user);
        // 为空的话 说明 数据库查询错误
        if (user1 == null) {
            return null;
        }
        // 查询成功后 返回秘钥
        return UUID.randomUUID().toString();
    }

    @Override
    public PageResult findUserList(PageResult pageResult) {
        // 获取总记录
        long total = userMapper.findTotal();
        // 根据 查询页数 和 查询条数 来确定分页的 规律
        int start = (pageResult.getPageNum() - 1) * pageResult.getPageSize();
        int size = pageResult.getPageSize();
        String query = pageResult.getQuery();
        List<User> userList = userMapper.findUserList(start, size, query);

        return pageResult.setTotal(total).setRows(userList);
    }

    @Override
    public void updateStatue(User user) {
        user.setUpdated(new Date());
        userMapper.UpdateStatue(user);
    }

    @Override
    public void deleteUserById(User user) {
        userMapper.deleteById(user);
    }

    @Override
    public void addUser(User user) {
        // 设置默认值
        user.setStatus(true).setCreated(new Date()).setUpdated(user.getCreated());
        // 将密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.addUser(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public void updateUserById(User user) {
        user.setUpdated(new Date());
        userMapper.updateUserById(user);
    }
}
